package com.zy.mc_module.ui.setting;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.hwangjr.rxbus.RxBus;
import com.makeramen.roundedimageview.RoundedImageView;
import com.zy.mc_module.R;
import com.zy.mc_module.base.BaseActivity;
import com.zy.mc_module.common.Constant;
import com.zy.mc_module.common.RxBusCode;
import com.zy.mc_module.mvp.bean.InvitationBean;
import com.zy.mc_module.mvp.bean.UserBean;
import com.zy.mc_module.mvp.contract.UserContract;
import com.zy.mc_module.mvp.presenter.UserPresenter;
import com.zy.mc_module.utils.AliOssUtils;
import com.zy.mc_module.utils.CameraUtils;
import com.zy.mc_module.utils.CompressUtils;
import com.zy.mc_module.utils.GlideUtil;
import com.zy.mc_module.utils.Logs;
import com.zy.mc_module.utils.NoDoubleUtil;
import com.zy.mc_module.utils.StatusBarUtil;
import com.zy.mc_module.utils.StringsUtils;
import com.zy.mc_module.utils.ToastUtil;
import com.zy.mc_module.utils.UserUtils;
import com.zy.mc_module.view.CustomHeadLayout;
import com.zy.mc_module.view.CustomTextView;
import com.zy.mc_module.wheel.dialog.CommonDialog;
import com.zy.mc_module.wheel.dialog.LoadingDialog;
import com.zy.mc_module.utils.retrofit.AppUrl;
import com.zy.mc_module.utils.retrofit.error.ThdException;
import com.zy.mc_module.wheel.wheelview.pickerview.builder.TimePickerBuilder;
import com.zy.mc_module.wheel.wheelview.pickerview.view.TimePickerView;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Date 19/3/16
 * @Author dq
 * 个人信息
 */
public class AccountActivity extends BaseActivity<UserContract.View, UserPresenter> implements UserContract.View {

    @BindView(R.id.customhead)
    CustomHeadLayout customhead;
    @BindView(R.id.account_userimg)
    RoundedImageView iv_userimg;
    @BindView(R.id.account_userName)
    CustomTextView tv_userName;
    @BindView(R.id.account_tel)
    CustomTextView tv_tel;
    @BindView(R.id.account_nickname)
    CustomTextView tv_nickname;
    @BindView(R.id.account_sex)
    CustomTextView tv_sex;
    @BindView(R.id.account_birth)
    CustomTextView tv_birth;
    @BindView(R.id.account_invite)
    CustomTextView tv_invite;
    @BindView(R.id.account_sure)
    Button bt_sure;

    private String[] sexs = new String[]{"保密", "男", "女",};
    private int type;//0登录进  1我的进

    @Override
    protected UserPresenter createPresenter() {
        return new UserPresenter();
    }

    @Override
    protected boolean isNeedRxBus() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_account;
    }

    @Override
    protected void initView() {
        StatusBarUtil.setImmersiveStatusBar(this);
        type = getIntent().getIntExtra("type", 1);
        if (type == 0) {
            //从登录页进入的
            customhead.setLeftVis(false);
            customhead.setRightVis(true);
            bt_sure.setVisibility(View.VISIBLE);
        } else {
            //从我的进入
            customhead.setLeftVis(true);
            customhead.setRightVis(false);
            bt_sure.setVisibility(View.GONE);
        }
        customhead.setLeftClickListener(view -> onBackPressed());
        customhead.setRightClickListener3(view -> onBackPressed());
        //获取用户信息
        presenter.getUserInfo(context);

    }

    /***
     * 完成跳过
     */
    @OnClick(R.id.account_sure)
    public void sure() {
        onBackPressed();
    }

    /***
     * 更换头像
     */
    @OnClick(R.id.account_userimg)
    public void head() {
        if (NoDoubleUtil.isFastClick()) {
            new CommonDialog(context, Constant.selectImg, position -> {
                if (position == 0) {
                    //拍照
                    CameraUtils.openCameraImage(this);
                } else if (position == 1) {
                    //从相册选取
                    CameraUtils.openLocalImage(this);
                }
            }).show();
        }
    }

    /***
     * 昵称和邮箱
     */
    @OnClick(R.id.account_relative_nickname)
    public void name(View view) {
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_editor, null);
        CommonDialog dialog = new CommonDialog(context, R.style.BottomKeyboardDialog, dialogView);
        EditText et_con = dialogView.findViewById(R.id.editor_dialog_edit);
        TextView tv_dis = dialogView.findViewById(R.id.editor_dialog_dis);
        TextView tv_sure = dialogView.findViewById(R.id.editor_dialog_sure);
        et_con.setText(tv_nickname.getText());
        et_con.setSelection(tv_nickname.getText().length());
        tv_sure.setOnClickListener(v -> {
            if (!StringsUtils.isEmpty(et_con)) {
                tv_nickname.setText(StringsUtils.getText(et_con));
                //设置昵称
                presenter.editUserInfo(context, AppUrl.EDIT_NICKNAME, StringsUtils.getText(et_con));
                dialog.dismiss();
            } else {
                ToastUtil.showShort("昵称不能为空");
            }
        });
        tv_dis.setOnClickListener(v -> dialog.dismiss());
        dialog.show();
    }

    /***
     * 性别
     */
    @OnClick(R.id.account_relative_sex)
    public void sex() {
        if (NoDoubleUtil.isFastClick()) {
            new CommonDialog(context, sexs, position -> {
                tv_sex.setText(sexs[position]);
                //设置性别
                presenter.editUserInfo(context, AppUrl.EDIT_SEX, position + "");
            }).show();
        }
    }

    /***
     * 出生日期
     */
    @OnClick(R.id.account_relative_birth)
    public void birth() {
        if (NoDoubleUtil.isFastClick()) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar start = Calendar.getInstance();
            start.set(Calendar.YEAR, 1916);
            Calendar end = Calendar.getInstance();
            end.setTimeInMillis(end.getTimeInMillis() - (86400000L));
            TimePickerView pvTime = new TimePickerBuilder(context, (date, v) -> {
                tv_birth.setText(format.format(date));
                //设置生日
                presenter.editUserInfo(context, AppUrl.EDIT_BIRTH, format.format(date));
            }).isDialog(true).setRangDate(start, end).setDate(end)
                    .setCancelColor(getResources().getColor(R.color.colorPrimary))
                    .setSubmitColor(getResources().getColor(R.color.colorPrimary))
                    .build();
            try {
                //如果设置过时间,下次打开显示选择的时间
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(df.parse(tv_birth.getText().toString()));
                pvTime.setDate(calendar);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            pvTime.show();
        }
    }

    /***
     * 获取用户信息
     * @param userBean
     */
    @Override
    public void onUserInfoSuccess(UserBean userBean) {
        if (null == userBean) {
            return;
        }
        if (null != CameraUtils.imageCrop) {
            GlideUtil.displayImage(iv_userimg, CameraUtils.imageCrop, R.mipmap.default_user_head);
        }
    }

    /***
     * 邀请信息
     */
    @Override
    public <T> void onSuccess(T t, int type) {
        if (type == 1) {
//            CkCenterBean bean = (CkCenterBean) t;
//            if (null != bean) {
//                tv_invite.setText(AppTools.setInvite(bean, 1));
//            }

            //邀请人信息
            InvitationBean.InvitationInfoBean bean = (InvitationBean.InvitationInfoBean) t;
            if (!StringsUtils.isEmpty(bean)) {
                if (bean.flagInviteUser) {
                    String identity = bean.referenceIdentity == null ? bean.userLevelName : bean.referenceIdentity;
                    String nickname = bean.nickname == null ? bean.userName : bean.nickname;
                    tv_invite.setText(identity + " " + nickname);
                } else {
//                    tv_invite.setText("没有大佬邀请我加入哦");
                    tv_invite.setText("");
                }
            }
        }
    }

    /***
     * 获取用户数据失败
     * @param error
     */
    @Override
    public void onError(ThdException error) {
        ToastUtil.showShort(error.message);
        //没网络或者加载失败,显示储存的旧数据,和新数据误差应该很小
        if (null != UserUtils.getUser()) {
            onUserInfoSuccess(UserUtils.getUser());
        }
    }

    /***
     * 拍照/相册回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //拍照
            case CameraUtils.GET_IMAGE_BY_CAMERA:
                if (resultCode == RESULT_OK && null != CameraUtils.imageUriFromCamera) {
                    // 对图片进行裁剪
                    CameraUtils.cropImage(this, CameraUtils.imageUriFromCamera);
                }
                break;

            //相册
            case CameraUtils.GET_IMAGE_BY_PHOTO:
                if (resultCode == RESULT_OK && null != data.getData()) {
                    // 对图片进行裁剪
                    CameraUtils.cropImage(this, data.getData());
                }
                break;

            // 裁剪图片后结果
            case CameraUtils.CROP_IMAGE:
                if (resultCode == RESULT_OK & null != CameraUtils.imageCrop) {
                    //显示裁剪后的图片
                    GlideUtil.displayImage(iv_userimg, CameraUtils.imageCrop, R.mipmap.default_user_head);
                    compressImg(Arrays.asList(CameraUtils.imageCrop));
                }
                break;
        }
    }

    /***
     * 压缩图片
     * @param paths
     */
    public void compressImg(List<String> paths) {
        AliOssUtils.getInstance().init(this);
        AliOssUtils.getInstance().uploadFile(new AliOssUtils.UploadFileListener() {
            @Override
            public void uploadProgress(String path, long currentSize, long totalSize) {

            }

            @Override
            public void uploadSuccess(String url) {
                Logs.Log_e("czyyy",url);
            }

            @Override
            public void uploadFailed(String message) {
                Logs.Log_e("czyyy",message);
            }
        },paths.get(0));
        if (paths.size()>0){
            return;
        }
        LoadingDialog dialog = new LoadingDialog(context);
        CompressUtils.compressUploadMore(context, paths, true, new CompressUtils.OnMyCompressListener() {
            @Override
            public void onStart() {
                dialog.show();
            }

            @Override
            public void complete(List<String> paths) {
                dialog.dismiss();
                //头像上传成功
                if (paths.size() > 0)
                    AliOssUtils.getInstance().uploadFile(new AliOssUtils.UploadFileListener() {
                        @Override
                        public void uploadProgress(String path, long currentSize, long totalSize) {

                        }

                        @Override
                        public void uploadSuccess(String url) {
                            Logs.Log_e("czyyy",url);
                        }

                        @Override
                        public void uploadFailed(String message) {
                            Logs.Log_e("czyyy",message);
                        }
                    },paths.get(0));
                    //presenter.editUserInfo(context, AppUrl.EDIT_HEADIMG, paths.get(0));
            }

            @Override
            public void onError(Throwable throwable) {
                ToastUtil.showShort(throwable.getMessage());
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (type == 0) {
            RxBus.get().post(RxBusCode.REFRESHUSER_GIFTBAG, "");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CameraUtils.imageCrop = null;
    }
}
